<template>
  <div class="w-full h-full p-8 bg-cover bg-[url('@/assets/images/wallpaper_404.jpeg')]">
    <div class="flex flex-col h-full justify-between">
      <!-- 消息窗口 -->
      <div class="h-full">
        <template v-for="item in chatStore.getMessageList">
          <div class="chat " :class="item.self?'chat-end':'chat-start'">
            <div class="chat-bubble " :class="item.color">
              {{ item.message }}
            </div>
          </div>
        </template>
      </div>

      <!--消息输入框-->
      <div class="flex flex-row justify-between items-center gap-2 p-2">
        <label class="input h-12 w-full">
          <input type="text" class="grow " v-model="inputText" placeholder="input ..."/>
        </label>
        <button class=" btn btn-info w-24" @click="clickSend">
          Sent
        </button>
      </div>

    </div>
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import AlertMessage from "@/views/components/alert_message";
import {useChatStore} from "@/stores/chat.ts";
import {ChatMsg} from "@/models/task";

const chatStore = useChatStore();
/**
 * 文字消息相关
 */
//输入的文本框内容
const inputText = ref("");

const EnterKeydown = (event) => {
  if (event.key === 'Enter' && (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') ) {
      event.preventDefault(); //阻止默认行为
      clickSend();
  }
};

onMounted(() => {
  window.addEventListener('keydown', EnterKeydown);
});

onUnmounted(() => {
  window.removeEventListener('keydown', EnterKeydown);
});

/**
 * 发送文本消息
 */
const clickSend = async () => {
  let msg = inputText.value.trim()
  if ((/^\[.*]$/.test(msg))) {
    msg = msg.substring(1, msg.length - 1);
  }
  console.debug("clickSend... ", msg)
  if (msg !== "") {
    console.log("chatStore.peerIp =", chatStore.peerIp)

    let message = new ChatMsg(msg, true);

    if (await window.chat.updSend(message.message, chatStore.peerIp)) {
      chatStore.addToList(message);
    } else {
      message.isFail = true
      chatStore.addToList(message);
      AlertMessage.warning("消息发送失败了");
    }
    inputText.value = "";
  }
}
const retrySend = async (msgId) => {
  console.debug("retrySend... msgId=", retrySend)
  if (msg !== "") {
    console.log("chatStore.remoteIp =", chatStore.remoteIp)

    let message = chatStore.getMessageById(msgId);
    if (await window.chat.updSend(message.message, chatStore.peerIp)) {
      message.isFail = false;
    } else {
      message.isFail = true;
      AlertMessage.warning("消息发送失败了");
    }
    inputText.value = "";
  }
}

</script>

<style lang="scss" scoped>

</style>
